<template>
  <AddOrEditDialog
    ref="addOrEditDialogRef"
    :form="form"
    title="课程"
    :formHeader="formHeader"
    :url="$urls.API_URL_BACKSTAGE_SCHOOLCOURSE_MANAGE"
    :action="action"
    @beforeSubmit="beforeSubmit"
    @afterSubmitSuccess="afterSubmitSuccess"
  >
    <!--部门下拉-->
    <template #departmentId>
      <SchoolDepartmentSelect
        v-model="form.departmentId"
        clearable/>
    </template>

    <!--专业下拉-->
    <template #majorId>
      <SysMajorTreeSelect
        v-model="form.majorId"
        clearable/>
    </template>

    <template #teacherId>
      <el-autocomplete
        v-model="state"
        clearable=true
        @select="handleSelect"
        :fetch-suggestions="querySearch"
        placeholder="输入课程负责教师"
      >
      </el-autocomplete>
    </template>

    <!--是否推荐-->
    <template #recommend>
      <el-radio-group v-model="form.recommend" class="ml-4">
        <el-radio :label="true">是</el-radio>
        <el-radio :label="false">否</el-radio>
      </el-radio-group>
    </template>

  </AddOrEditDialog>
</template>

<script lang="ts" setup>
// 导入部门下拉组件
import SchoolDepartmentSelect from '@/components/uem/SchoolDepartmentSelect.vue';
// 导入专业下拉组件
import SysMajorTreeSelect from '@/components/uem/SysMajorTreeSelect.vue';
// 引入添加编辑模块
import AddOrEditDialog from '@/components/base/table/form/AddOrEditDialog.vue';
import {
  onMounted, defineExpose, defineProps, getCurrentInstance, reactive, ref, withDefaults, onUpdated,
} from 'vue';
// 引入表格相关
import { TableColumn, FormHeader, TableData } from '@/types/interface/base_interface';
// 引入学生对象
import { SchoolCourse } from '@/types/interface/school_interface';
import {
  departmentTypeDict, Option, getDict,
} from '@/api/dict';
import Request from '@/api/request/request';

const { proxy } = getCurrentInstance();
const teacherList = ref<any>([]);
  // 接收父容器参数
  interface Props {
    table: TableData, // 偷懒写法
    action?: string, // 表单的处理类型，post表示添加，put表示编辑
  }
interface RestaurantItem {
  id: number
  value: string
}
// 是否推荐课程
const Ifrecommend = ref<boolean>(false);
// 课程负责人
const state = ref<string>('');
// 从后端获取到的值，将展示到列表下拉
const restaurants = ref<RestaurantItem[]>([]);
const props = withDefaults(defineProps<Props>(), {
  action: 'post',
});

// 课程负责人
const teacherId = ref();
// let teacherId = String();
const DoteacherId = async () => {
  console.log(teacherId.value);
  teacherList.value = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLTEACHER_MANAGE, null, {
    params: {
      name: teacherId.value,
    },
  }).get();
};

// 可以自定义处理方法，也可以使用element-plus定义的方法
const filter = (arr:[]) => {
  const list: [] = [];
  let obj = {};
  arr.forEach((item:any) => {
    obj = {
      value: item.name,
      id: item.id,
    };
    list.push(obj);
  });
  return list;
};

const querySearch = async (queryString: string, cb: any) => {
  let resData:any = await new Request(proxy.$urls.API_URL_BACKSTAGE_SCHOOLTEACHER_MANAGE, null, {
    params: {
      name: queryString,
    },
  }).get();
  if (resData.code === 200) {
    const { data } = resData.data;
    const list = filter(data);
    console.log(list);
    cb(list);
  }
};

onMounted(() => {
  DoteacherId();
});

// 初始化课程类别字典
const courseType:Option[] = await getDict('课程性质', 'number');
// 表单元素
const formHeader = ref<FormHeader[]>([
  {
    label: '所属部门',
    prop: 'departmentId',
    type: 'custom',
  },
  {
    label: '专业',
    prop: 'majorId',
    type: 'custom',
  },
  {
    label: '课程负责人',
    prop: 'teacherId',
    type: 'custom',
  },
  {
    label: '课程名称',
    prop: 'name',
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '课程类型',
    prop: 'type',
    type: 'select',
    dict: courseType,
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '学分',
    prop: 'credit',
  },
  {
    label: '学时',
    prop: 'period',
  },
  {
    label: '推荐',
    prop: 'recommend',
    type: 'custom',
  },
]);
// 表单对象
const form = ref<SchoolCourse>();

// onUpdated(() => {
//   form.value!.recommend = false;
// });

// 在点击选中建议，也就是点击从后端获取到的数据后，完成相对应的事件，例如查询某条数据
const handleSelect = (value: RestaurantItem) => {
  form.value!.teacherId = value.id;
  state.value = value.value;
};
const addOrEditDialogRef = ref(); // 表单ref对象
let formInit:SchoolCourse; // 记录表单第一次传入的值,用于表单重置恢复初始值使用
// 打开对话框，供父组件调用，传入表单对象
const openDialog = (schoolCourse: SchoolCourse) => {
  formInit = { ...schoolCourse }; // 获取初始值，这里要做深拷贝，避免与form对象引用的地址一致，导致无法恢复初始值
  form.value = schoolCourse;
  if (form.value.schoolTeacher && props.action === 'put') {
    state.value = form.value.schoolTeacher.name;
  } else {
    state.value = '';
  }
  // 打开对话框
  addOrEditDialogRef.value!.openDialog();
};
// 提交表单成功后的钩子函数
const afterSubmitSuccess = () => {
  // 让表单恢复为传入对象时的初始值，注意要深度拷贝，避免初始值收到污染
  form.value = { ...formInit };
  state.value = '';
};
  // 暴露组件给父容器使用
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>

</style>
